package newpackage;

import java.net.*;
import java.io.*;

// A server that says 'hello'
// Lab session: here are the things you should do
// 
// 1. catch command line error (missing  or wrong argument) and exit with an error message
// 2. write a cleanUp method that close streams and sockets no matter what! put calls to this method in the rigt place
// 3. have the server hold a list of connected clients (ConnectionHandler)
// 4. add at least one public method removeClient (ConnectionHandler client) that will be used in ConnectionHandler


class HelloServer {
    public static void main(String[] args) {
        int port = Integer.parseInt(args[0]);
        ServerSocket server = null;
        ChatAdministration cAdmin = new ChatAdministration();
        try {
            server = new ServerSocket(port);
        } catch (IOException ioe) {
            System.err.println("Couldn't run server on port " + port);
            return;
        } 
            while(true) 
            {
                try 
                {
                    Socket connection = server.accept();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    String userName = reader.readLine();
                    if(userName != null && !userName.equals(""))
                    {
                        ConnectionHandler handler = new ConnectionHandler(connection, cAdmin, userName);
                        cAdmin.addUser(handler);
                        new Thread(handler).start();
                    }
                }
                catch (IOException ioe1) 
                {
                }
            }
   	}
}     
